using DG.Tweening;
using DG.Tweening.Core;
using TinaX.Tween;
using UnityEngine;

namespace Nekonya.Components.SceneMechanism
{
    /// <summary>
    /// 场景机关 - 门
    /// </summary>
    [RequireComponent(typeof(InteractiveObservationComponent))]
    public class Door : MonoBehaviour
    {
        public InteractiveObservationComponent InteractiveObservation;
        public Transform _Door;

        public Collider _Collider;

        private bool IsOpen = false;

        private TweenerCore<Quaternion, Vector3, DG.Tweening.Plugins.Options.QuaternionOptions> Dotweener;

        private void Awake()
        {
            if (InteractiveObservation == null)
                InteractiveObservation = this.GetComponent<InteractiveObservationComponent>();
            if (_Collider == null)
                _Collider = this.GetComponent<Collider>();

            _Collider.isTrigger = false;

            InteractiveObservation.DoAction += DoOpenOrCloseDoor;
        }

        private void OnDestroy()
        {
            InteractiveObservation.DoAction -= DoOpenOrCloseDoor;
        }


        private void DoOpenOrCloseDoor()
        {
            if (!IsOpen)
            {
                
                Debug.Log("开门");
                //开门
                if (Dotweener != null)
                {
                    Dotweener.Kill();
                    Dotweener = null;
                }
                Dotweener = _Door.DOLocalRotate(new Vector3(-90, 0, 90), 1.5f, RotateMode.Fast);
                IsOpen = true;
                _Collider.isTrigger = true;
            }
            else
            {
                Debug.Log("关门");
                if (Dotweener != null)
                {
                    Dotweener.Kill();
                    Dotweener = null;
                }
                Dotweener = _Door.DOLocalRotate(new Vector3(-90, 0, 0), 1f, RotateMode.Fast);
                IsOpen = false;
                _Collider.isTrigger = false;
            }
        }

    }
}
